// packageA/pages/cleanWorkList/cleanWorkList.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:{},
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //搜索关键词
    searchValue:'',
    //状态筛选
    optionState:[
      {text: '所有状态', value: -1},
      {text: '待接单', value: 2},
      {text: '处理中', value: 3},
			{text: '已完成', value: 1},
			{text: '待验收', value: 4}
    ],
		valueState: -1,
		//接单人筛选
    optionReceive:[
      {text: '所有工单', value: 0},
      {text: '我接单的', value: 1}
    ],
    valueReceive: 0,
    //登录用户
    user: null,
    //开始时间
    startTime: '开始日期',
    //开始时间选择框
    showStartTime:false,
    //结束时间
    endTime: '结束日期',
    //结束时间选择框
    showEndTime:false,
    //当前时间
    currentStart: new Date().getTime(),
    currentEnd: new Date().getTime(),
    //最小时间
    minDate2:null,
    //最大时间
    maxDate1: new Date().getTime(),
    maxDate2: new Date().getTime(),
    //时间格式
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } 
      return value
		},
		//查询条件，项目id
		queryProjectIds: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let user=app.globalData.userInfo;
    if(user){
      this.setData({
        user: user
			})
			this.getList();
    }else{
      wx.redirectTo({
        url: "/pages/login/login?fromCleanWork="+'1'
      })
    }
	},
	
	//查询根据地
	getBaseArea(){
		Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
		});
		
		let user = this.data.user;
		let dObj = user.departObj[0];

		let param = {
      isAuth: false,
      className: 'baseAreaManagement',
      data: {
				searchAll: true,
				selectFields: ['id','name','departsId','projectsId'],
				nbl: Base64.encode(util.timeFormatDay(new Date()))
      }
		}

		//区分什么级别的用户登录（一级部门、大区、项目）
		if(dObj.level==1){
			//一级
			param.data.departsId = dObj.id;
		}else if(dObj.isProject){
			//项目
			param.data.projectsId = dObj.id;
		}else if(dObj.isRegion){
			//大区
			param.data.departsId = dObj.companyId;
		}else{
			//无数据
			this.notDatas();
			//都不是的不能查询
			return;
		}

		CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;
        console.log('根据地');
				console.log(result); 
				
				//取出项目id
				let proIds = [];
				result.forEach(item=>{
					proIds = proIds.concat(item.projectsId);
				});

				//再把数据权限加进去
				proIds = proIds.concat(user.dataAuthorityOfUser.depart);
		
				//去重
				proIds = util.arrayRepeatEmpty(proIds);

				console.log('所有项目');
				console.log(proIds);

				if(proIds.length){
					this.setData({
						queryProjectIds: proIds
					})

					//获取工单列表
					this.getList();
				}
				
      }else{
				//无数据
				this.notDatas();
			}
    }).catch((error) => {
      //无数据
			this.notDatas();
    })
	},

  //获取列表数据
  getList(){
		let dObj = this.data.user.departObj[0];
		let dataObj={
      memberId:dObj.id,
			selectFields: ['id','type','state','content','phoneNumber','userName','time','memberId','state','createDate','projectName'],
      nbl: Base64.encode(util.timeFormatDay(new Date())),
      sort: {
				createDate: -1
			},
			page: {
				page: this.data.page,
				pageSize: 10
			}
		}
        //模糊查询
        if(this.data.searchValue){
          dataObj['userName']='%' +this.data.searchValue+ '%';
        }
           //创建时间
           if(this.data.startTime!='开始日期' && this.data.endTime!='结束日期'){
            dataObj.complex=[{
              and: {
                createDate: {
                  ">=": this.data.startTime + " 00:00:00",
                  "<=": this.data.endTime + " 23:59:59"
                }
              }
            }]  
          }
		let param = {
      isAuth: false,
      className: 'rabbitLog',
      data: dataObj
    }
    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;

        result.forEach(item => {
          //状态
          switch(item.state){
            case 0:
              item.self_state='未读';
              item.self_stateClass='c-1';
              break;
            case 1:
              item.self_state='已读';
              item.self_stateClass='c-2';
              break;
          }
        });

        console.log('保洁工单列表');
        console.log(result);

        this.setData({
          list: this.data.list.concat(result)
        })
        Toast.clear();
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
          Toast.clear();
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
      Toast.clear();
    })
	},
	
	//无数据
	notDatas(){
		this.setData({
			showNothing: true
		})
		Toast.clear();
	},

  //全部标记已读
  allMarkedAsRead(){
    let dObj = this.data.user.departObj[0];
    console.log(dObj);
    let param = {
      className: 'rabbitLog',
      data: {
        filter: {
          memberId: dObj.id
        },
        update: {
          set: {
            state: 1
          }
        }
      }
    }
    CommonService.goUpdate(param).then(res => {
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('操作成功');
        //刷新列表和页码
        this.refreshListAndPage();
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })
  },



   //显示开始时间
   onShowStartTime(){
    this.setData({
			showStartTime: true
    })
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value.trim(),
    })
  },

  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  },

  //跳转添加
  goToAdd(){
    wx.navigateTo({
      url: "/packageA/pages/cleanWorkAdd/cleanWorkAdd"
    })
  },

  //跳转编辑
  goToEdit(e){
    let detail=e.currentTarget.dataset.detail;
    let obj={
      id: detail.id
    }
    wx.navigateTo({
      url: "/packageA/pages/cleanWorkAdd/cleanWorkAdd?paramObj="+JSON.stringify(obj)
    })
  },

  //跳转详情
  goToLook(e){
    let detail=e.currentTarget.dataset.detail;
    let obj={
      id: detail.id
    }
    wx.navigateTo({
      url: "/packageB/pages/personnelErrorMsgDetail/personnelErrorMsgDetail?paramObj="+JSON.stringify(obj)
    })
  },

  //跳转处理
  goToHandle(e){
    let detail=e.currentTarget.dataset.detail;
    let obj={
      id: detail.id,
      projectName:detail.project.name,
      submitter:detail.submitter.id,
      handlerName:detail.handler.name.split("-")[0],
      handlerId:detail.handler.id,
      problem:detail.problem,
      projectId:detail.project.id
    }

    console.log(detail);

    wx.navigateTo({
      url: "/packageA/pages/cleanWorkHandle/cleanWorkHandle?paramObj="+JSON.stringify(obj)
    })
  },

  //删除
  onDelete(e){
    Dialog.confirm({
      title: '确定删除此工单吗',
      confirmButtonText:'确定',
      cancelButtonText:'不删除了'
    }).then(() => {
      let detail=e.currentTarget.dataset.detail;

      let param={
        className:"cleanKeepingOrder",
        data:{
          id:detail.id
        }
      }

      CommonService.goDelete(param).then(res=>{
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('已删除');
          //刷新列表和页码
          this.refreshListAndPage();
        }else{
          Toast.fail('操作失败');
        }
      }).catch((error) => {
        Toast.fail('操作失败');
      })

    }).catch(() => {
    });
  },

  //预览图片
  onPreviewImage(e) {
    let detail = e.target.dataset.detail;
    let src = e.target.dataset.src;

    let newArr=[];
    for(let i=0;i<detail.length;i++){
      newArr.push(detail[i].url);
    }

    wx.previewImage({
      current: src,
      urls: newArr
    })
  },

  //选择状态
  onChangeState({detail}) {
    this.setData({
      valueState: detail
    })
    this.refreshListAndPage();
	},
	
	//选择我接单的/所有
	onChangeReceive({detail}) {
    this.setData({
      valueReceive: detail
    })
    this.refreshListAndPage();
	},

  //接单
  onStart(e){
    Dialog.confirm({
      title: '确定接单吗',
      confirmButtonText:'确定',
      cancelButtonText:'取消'
    }).then(() => {

			let detail=e.currentTarget.dataset.detail;
			let obj={
				id: detail.id,
				//是否接单（为了区分编辑）
        isReceive: true,
        projectId:detail.project.id,
        place:detail.place,
        problem:detail.problem,
        projectName:detail.project.name
      }
      console.log(detail);
			wx.navigateTo({
				url: "/packageA/pages/cleanWorkAdd/cleanWorkAdd?paramObj="+JSON.stringify(obj)
			})
    }).catch(() => {
    });
  },

  //完成
  onComplete(e){
    Dialog.confirm({
      title: '确定完成此工单吗',
      confirmButtonText:'确定',
      cancelButtonText:'取消'
    }).then(() => {
      let detail=e.currentTarget.dataset.detail;

      let param={
        className:"cleanKeepingOrder",
        data:{
          id: detail.id,
          //状态 1已完成,2未受理,3受理中
          state: 1,
          //完成时间
          completionTime: util.timeFormat(new Date())
        }
      }

      CommonService.goSave(param).then(res=>{
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('已接单');
          //刷新列表和页码
          this.refreshListAndPage();
        }else{
          Toast.fail('操作失败');
        }
      }).catch((error) => {
        Toast.fail('操作失败');
      })

    }).catch(() => {
    });
  },



  //隐藏开始时间
  onCloseStartTime(){
    this.setData({
			showStartTime: false
    })
  },

  //确认开始时间
  onConfirmStartTime(e) {
    this.setData({
      currentStart: e.detail,
      minDate2:e.detail,
      startTime:util.timeFormatDay(e.detail),
    })
    this.onCloseStartTime();

    if(this.data.endTime!='结束日期'){
      this.refreshListAndPage();
    }  
  },

  //显示结束时间
  onShowEndTime(){
    this.setData({
			showEndTime: true
    })
  },

  //隐藏结束时间
  onCloseEndTime(){
    this.setData({
			showEndTime: false
    })
  },

  //确认结束时间
  onConfirmEndTime(e) {
    this.setData({
      currentEnd: e.detail,
      maxDate1:e.detail,
      endTime:util.timeFormatDay(e.detail),
    })
    this.onCloseEndTime();

    if(this.data.startTime!='开始日期'){
      this.refreshListAndPage();
    }
  },

  //清除时间
  onCancelTime(){
    this.setData({
      startTime: '开始日期',
      endTime: '结束日期'
    })
    
    this.onCloseStartTime();
    this.onCloseEndTime();
    this.refreshListAndPage();
	},
	
	//跳转验收评价
  goToCheck({currentTarget}){
    let detail=currentTarget.dataset.detail;
    let obj={
      id: detail.id
    }
    wx.navigateTo({
      url: "/packageA/pages/cleanWorkCheck/cleanWorkCheck?paramObj="+JSON.stringify(obj)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})